<style scoped>
.excalidraw-demo {
  padding: 20px;
}

.demo-container {
  display: flex;
  margin-top: 20px;
  gap: 20px;
}

.control-panel {
  flex: 1;
  max-width: 400px;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.excalidraw-panel {
  flex: 2;
}

.json-preview {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: auto;
  max-height: 300px;
}

.json-preview pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>

<template>
  <div class="excalidraw-demo">
    <h1>Excalidraw组件演示</h1>

    <div class="demo-container">
      <div class="control-panel">
        <h3>控制面板</h3>
        <el-form label-width="100px">
          <el-form-item label="暗黑模式">
            <el-switch v-model="darkMode"></el-switch>
          </el-form-item>
          <el-form-item label="只读模式">
            <el-switch v-model="viewMode"></el-switch>
          </el-form-item>
          <el-form-item label="网格模式">
            <el-switch v-model="gridMode"></el-switch>
          </el-form-item>
          <el-form-item label="禅模式">
            <el-switch v-model="zenMode"></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveData">保存数据</el-button>
            <el-button @click="loadData">加载数据</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="exportImage">导出图片</el-button>
            <el-button type="warning" @click="exportSVG">导出SVG</el-button>
            <el-button type="danger" @click="clearCanvas">清空画板</el-button>
          </el-form-item>
        </el-form>

        <div class="json-preview">
          <h4>JSON数据预览</h4>
          <pre>{{ formattedJson }}</pre>
        </div>
      </div>

      <div class="excalidraw-panel">
        <h3>Excalidraw画板</h3>
        <ExcalidrawComponent
          ref="excalidrawComponent"
          :resourceJson="resourceJson"
          :darkMode="darkMode"
          :viewMode="viewMode"
          :gridMode="gridMode"
          :zenMode="zenMode"
          height="600px"
          @change="handleExcalidrawChange"
          @loaded="handleExcalidrawLoaded"
        />
      </div>
    </div>
  </div>
</template>

<script>
import ExcalidrawComponent from '@/components/ExcalidrawComponent.vue'

export default {
  name: 'ExcalidrawDemo',
  components: {
    ExcalidrawComponent
  },
  data() {
    return {
      resourceJson: null,
      darkMode: true,
      viewMode: false,
      gridMode: true,
      zenMode: false,
      excalidrawLoaded: false,
      jsonData: null
    }
  },
  computed: {
    formattedJson() {
      if (!this.jsonData) return '无数据'
      try {
        // 格式化JSON字符串，限制长度以避免界面过长
        const parsed = JSON.parse(this.jsonData)
        const elements = parsed.elements || []
        const appState = parsed.appState || {}

        return JSON.stringify({
          elements: elements.length > 0 ?
            [{ ...elements[0], ...{ note: `共 ${elements.length} 个元素` } }] :
            [],
          appState: {
            theme: appState.theme,
            viewModeEnabled: appState.viewModeEnabled,
            // 其他状态省略...
          }
        }, null, 2)
      } catch (e) {
        return '无效的JSON数据'
      }
    }
  },
  mounted() {
    // 从本地存储加载上次保存的数据
    this.loadFromLocalStorage()
  },
  methods: {
    /**
     * 处理Excalidraw数据变更
     */
    handleExcalidrawChange(jsonData) {
      this.jsonData = jsonData
    },

    /**
     * 处理Excalidraw加载完成
     */
    handleExcalidrawLoaded() {
      this.excalidrawLoaded = true
      console.log('Excalidraw组件加载完成')
    },

    /**
     * 保存数据到本地存储
     */
    saveData() {
      if (!this.jsonData) {
        this.$message.warning('没有可保存的数据')
        return
      }

      try {
        localStorage.setItem('excalidraw-demo-data', this.jsonData)
        this.$message.success('数据已保存到本地存储')
      } catch (e) {
        this.$message.error('保存数据失败: ' + e.message)
      }
    },

    /**
     * 从本地存储加载数据
     */
    loadData() {
      this.loadFromLocalStorage()
    },

    /**
     * 从本地存储加载数据的实现
     */
    loadFromLocalStorage() {
      try {
        const savedData = localStorage.getItem('excalidraw-demo-data')
        console.log("🚀 ~ loadFromLocalStorage ~ savedData:", savedData)
        if (savedData) {
          this.resourceJson = savedData
          this.$message.success('已从本地存储加载数据')
        }
      } catch (e) {
        console.error('加载数据失败:', e)
      }
    },

    /**
     * 导出为图片
     */
    async exportImage() {
      if (!this.$refs.excalidrawComponent) {
        this.$message.warning('Excalidraw组件未加载')
        return
      }

      try {
        const blob = await this.$refs.excalidrawComponent.exportToImage()
        if (blob) {
          const url = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = 'excalidraw-export.png'
          link.click()
          URL.revokeObjectURL(url)
          this.$message.success('图片导出成功')
        } else {
          this.$message.warning('没有可导出的内容')
        }
      } catch (e) {
        this.$message.error('导出图片失败: ' + e.message)
      }
    },

    /**
     * 导出为SVG
     */
    async exportSVG() {
      if (!this.$refs.excalidrawComponent) {
        this.$message.warning('Excalidraw组件未加载')
        return
      }

      try {
        const svg = await this.$refs.excalidrawComponent.exportToSVG()
        if (svg) {
          const svgString = new XMLSerializer().serializeToString(svg)
          const blob = new Blob([svgString], { type: 'image/svg+xml' })
          const url = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = 'excalidraw-export.svg'
          link.click()
          URL.revokeObjectURL(url)
          this.$message.success('SVG导出成功')
        } else {
          this.$message.warning('没有可导出的内容')
        }
      } catch (e) {
        this.$message.error('导出SVG失败: ' + e.message)
      }
    },

    /**
     * 清空画板
     */
    clearCanvas() {
      if (!this.$refs.excalidrawComponent) {
        this.$message.warning('Excalidraw组件未加载')
        return
      }

      this.$confirm('确定要清空画板吗？此操作不可撤销。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.excalidrawComponent.clearCanvas()
        this.$message.success('画板已清空')
      }).catch(() => {
        this.$message.info('已取消清空操作')
      })
    }
  }
}
</script>

